package com.zzq.controller;

import com.zzq.context.BaseContext;
import com.zzq.pojo.Bidder;
import com.zzq.pojo.Result;
import com.zzq.service.BidderService;
import com.zzq.tools.JwtUtil;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/bidder")
@Validated
@Slf4j
public class BidderController {

    @Autowired
    private BidderService bidderService;

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^[a-zA-Z0-9_]{3,20}$") String username,@Pattern(regexp = "^[a-zA-Z0-9_]{6,20}$") String password,String companyName,String email,String address) {
       Bidder bidder=bidderService.findByBidderName(username);
       if(bidder==null){
           bidderService.register(username,password,companyName,email,address);
           return Result.success();
       }else {
           return Result.error(500,"用户名已占用");
       }
    }
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^[a-zA-Z0-9_]{3,20}$") String username, @Pattern(regexp = "^[a-zA-Z0-9_]{6,20}$") String password){
        Bidder bidder=bidderService.findByBidderName(username);
        if(bidder!=null){
            if(bidder.getPassword().equals(password)){
                Map<String, Object> claims=new HashMap<>();
                claims.put("id",bidder.getId());
                claims.put("username",username);
                String token= JwtUtil.getToken(claims);
                return Result.success(token);
            }else {
                return Result.error(500,"密码错误");
            }
        }else{
            return Result.error(500,"用户名错误");
        }
    }

    @PostMapping("/logout")
    public Result<String> logout() {

        BaseContext.removeCurrentId();

        log.info(BaseContext.getCurrentId());

        return Result.success();
    }


    @GetMapping("/AllBidder")
    public Result<List<Bidder>> AllBidder(){
        List<Bidder> bidder=bidderService.list();
        return Result.success(bidder);
    }

    @PutMapping("/deleteBidder")
    public Result deleteBidder(int id){
        bidderService.deleteBidder(id);
        return Result.success();
    }

    @PutMapping("/edit")
    public Result editBidder(@RequestBody Bidder bidder){
        bidderService.editBidder(bidder);
        return Result.success();
    }

    @GetMapping("/user")
    public Result<Bidder> getUser(String username){
        Bidder bidder=bidderService.findByBidderName(username);
        return Result.success(bidder);
    }

    @GetMapping("/findBidderByName")
    public Result<Bidder> getAllInfo(String name){
        Bidder bidder=bidderService.getAllInfo(name);
        return Result.success(bidder);
    }
}
